import Parser
import Lexer
import VarGlobales
import NodosArbol
import random
import ASTVisitor
import ParserInstrucciones
import LexerInstrucciones
import gc

class Interprete():
    def __init__(self,txtinst,txtcode):
        self.txtinst = txtinst
        self.txtcode = txtcode
        self.ast = None
        self.code = ""
        self.RandomName = ""
        
    def Settxtinst(self, val):
        self.txtinst = val
        
    def Settxtcode(self, val):
        self.txtcode = val
        
    def GenCode(self):
        self.GenName()
        self.code = "pr "+self.RandomName+"() \n"+"inicio \n" + self.txtinst +"\nfin \n"
        self.code += self.txtcode
        
        #print self.code #prueba
        
    def GenName(self):
        self.RandomName = ""
        for i in range(0,20):
            self.RandomName += str(chr(random.randint(65,90)))
            
    def ProcessStages(self):
        self.ast = None
        self.GenCode()
        VarGlobales.PilaVariables=NodosArbol.Pila()        
        l = Lexer.Lexer()
        p = Parser.parser(l.GetTokens())
        self.ast = p.parse(self.code)
        VarGlobales.ListaFunciones=self.ast.lista.lista
        
    def ProcessStages2(self):
        self.ast = None
        l = LexerInstrucciones.Lexer()
        p = ParserInstrucciones.parser(l.GetTokens())
        self.code = self.txtinst
        self.ast = p.parse(self.code)
        
    def Execute(self):
        self.ProcessStages()
        self.ast.ejecutar(self.RandomName,None)
        gc.collect()
        
    def Execute2(self):
        self.ProcessStages2()
        self.ast.ejecutar()
        gc.collect()
             
    def GenCodeRobot(self):
        self.ProcessStages()
        v = ASTVisitor.ASTGenCode()
        v.visit(self.ast)
        v.TraducirEtiquetas()
        return v.GetCodeIn() 